# -*- coding: utf-8 -*-
# @Time    : 2018/2/6 23:14
# @Author  : Soft
# @File    : service.py
from module.models import Class, db, Page, Record, Work
from module.TimeUtils import *
from config import QD_PREV
import logging

log = logging.getLogger('ClassService LOG')


class ClzService:
    def __init__(self):
        pass

    @staticmethod
    @db.atomic()
    def add(**clazz):
        return Class.insert(**clazz).execute()

    @staticmethod
    def add_stu_num(kid=None):
        """
        增加课程出勤学生数
        :param kid: 课程id
        :return:
        """
        try:
            with db.atomic():
                if Class.update(k_stu_num=Class.k_stu_num + 1).where(Class.id == kid).execute() > 0:
                    return True
                return False
        except BaseException as e:
            log.debug('增加课程签到人数异常--> %s' % e)
            return False

    @staticmethod
    @db.atomic()
    def remove(kid=0):
        try:
            Record.delete().where(Record.k == kid).execute()
            Work.delete().where(Work.k == kid).execute()
            return Class.delete_by_id(kid)
        except BaseException as e:
            log.debug("删除课程(id: %s)的记录失败--> %s" % (kid, e))
            return False

    @staticmethod
    def change(cid=0, **clazz):
        try:
            with db.atomic():
                Class.update(**clazz).where(Class.id == cid).execute()
                return True
        except BaseException as e:
            log.debug('修改异常--> %s' % e)
            return False

    @staticmethod
    def getById(kid):
        try:
            return Class.get_by_id(kid)
        except BaseException as be:
            log.error('Get Class[id=%s] Failure %s' % (kid, be))

    @staticmethod
    def class_count(year=None):
        try:
            if year:
                return Class.select().where(Class.k_time.startswith(year)).count()
            return Class.select().count()
        except BaseException as e:
            log.debug('统计课程数异常--> %s' % e)
            return 0

    @staticmethod
    def pages(page=1, size=12, year=2018, status=None):
        """
        课程分页查询 根据年份和状态
        """
        data = []
        if status:
            results = Class.select().where(Class.k_time.startswith(year), Class.k_status == status). \
                order_by(Class.k_time.asc()).paginate(page, size)
        else:
            results = Class.select().where(Class.k_time.startswith(year)). \
                order_by(Class.k_time.asc()).paginate(page, size)
        for result in results:
            data.append(result.to_dict())
        Page.result = data
        Page.page = page
        Page.limit = size
        Page.total = Class.select().where(Class.k_time.startswith(year)).count()
        return Page.to_dict()

    @staticmethod
    def is_has(kid):
        """
        查询课程是否存在
        :param kid: 课程id
        :return: 是否存在和课程数据
        """
        k = Class.find_by_id(pk=kid)
        if k.get('k_name'):
            return True, k
        return False, k

    @staticmethod
    def by_year(year='2018'):
        """
        通过年份获取已上或进行中的课程 后台作业和签到记录中下拉分类使用
        :param year: 年份
        """
        now_date = get_time(QD_PREV)
        clz = ClzService.query_sql('select id, k_name from class WHERE k_time LIKE %s and '
                                   'k_time <= %s order by k_time', str(year) + "%", now_date)
        if len(clz):
            clz.insert(0, {'k_name': u'全部课程', 'id': 0})
        else:
            clz.insert(0, {'k_name': u'暂无完成课程', 'id': 0})
        return clz

    @staticmethod
    def by_k_time(k_time):
        """
        通过开课时间获取课程
        :param k_time:
        :return: 是否成功和课程
        """
        try:
            clz = Class.select().where(Class.k_time.startswith(k_time)).get()
            return True, clz
        except BaseException as e:
            log.debug('通过开课时间获取课程异常--> %s' % e)
            return False, Class()

    @staticmethod
    def get_year_group():
        return ClzService.query_sql('select substring(k_time, 1, 4) as k_time from class '
                                    'group by substring(k_time, 1, 4)')

    @staticmethod
    def get_now_clazz():
        """
        获取当前正在进行的课程
        :return:
        """
        now_date = get_time(QD_PREV)
        clz = Class.select().where(Class.k_time <= now_date).order_by(
            Class.k_time.desc())
        if len(clz) > 0:
            return clz[0].to_dict()
        return None

    @staticmethod
    def get_next_clazz():
        """
        获取下一次课程
        :return:
        """
        now_date = get_time(QD_PREV)
        clz = Class.select().where(Class.k_time > now_date).order_by(
            Class.k_time.asc())
        if len(clz) > 0:
            return clz[0].to_dict()
        return None

    @staticmethod
    def query_sql(sql, *param):
        s = []
        for t in Class.raw(sql, *param):
            s.append(t.to_dict())
        return s
